package geektime.concurrent.part2.race;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;

/**
 * 多线程操作的共享数据类
 */
public class MultiThreadShareData extends ShareData{
    private static final String GEN_RANDOM_NUMBER_LATCH = "GEN_RANDOM_NUMBER_LATCH";

    private static final String SORT_COMPUTE_LATCH = "SORT_COMPUTE_LATCH";

    public MultiThreadShareData(int genRandomNumbersThreadQuantity, int sortComputeThreadQuantity) {
        concurrentSignalMap.put(GEN_RANDOM_NUMBER_LATCH, new CountDownLatch(genRandomNumbersThreadQuantity));
        concurrentSignalMap.put(SORT_COMPUTE_LATCH, new CountDownLatch(sortComputeThreadQuantity));
        // 该容器会设计并发操作，使用CopyOnWriteArrayList可以确保线程安全
        exchangeList = new CopyOnWriteArrayList<>();
    }

    public CountDownLatch getGenRandomLatch(){
        return (CountDownLatch) concurrentSignalMap.get(GEN_RANDOM_NUMBER_LATCH);
    }

    public CountDownLatch getSortComputeLatch(){
        return (CountDownLatch) concurrentSignalMap.get(SORT_COMPUTE_LATCH);
    }

    // 获取交换区容器的数据
    public List<Integer> getExchange() {
        return exchangeList;
    }

    // 通过int类型往交换区容器中添加数据
    public void addExchange(Integer num) {
        exchangeList.add(num);
    }

    // 通过数组往交换区容器中添加数据
    public void addExchange(Integer[] nums) {
        exchangeList.addAll(Arrays.asList(nums));
    }

}
